<?php

namespace app\common\library;

use think\facade\Cache;

class Utils
{
    /**
     * 生成单据号
     * @param $prefix 编号前缀
     */
    public static function createNo($prefix = ""){
        $date = date('Ymd');
        $CacheName = '$order_prefix'.($prefix ? '_'.$prefix : '').$date;

        $code = Cache::remember($CacheName, 1);
        Cache::inc($CacheName);
        $code = str_pad((string)$code,6,'0',STR_PAD_LEFT);
        return  $prefix.$date.$code;
    }

    public function putCsv(string $filename,Array $data): string {
        try {
            $filename = $filename.'.csv';
            $fileData = "";
            foreach ($data as $item) {
                $fileData .= $this->utfToGbk(join(',', $item))."\n";
            }

            $filePath =  '/storage/exports/' . $filename;
            // 将一个字符串写入文件
            file_put_contents(public_path().$filePath, $fileData);
            return $filePath;
        } catch (Exception $e){
            echo $e->getMessage();
        }
    }

    public function exportCsv($filename, $data) {
        $filename = $this->utfToGbk($filename.'.csv');
        $fileData = "";
        foreach ($data as $item) {
            $fileData .= $this->utfToGbk(join(',', $item))."\n";
        }

        $filesize = strlen($fileData);
        $fp = fopen('php://output', 'a');
        //返回的文件(流形式)
        header("Content-type: application/octet-stream;charset=utf-8");        //按照字节大小返回
        header("Accept-Ranges: bytes");        //返回文件大小
        header("Accept-Length: $filesize");        //这里客户端的弹出对话框，对应的文件名
        header("Content-Disposition: attachment; filename=".$filename);
        ob_clean();
        flush();
        //设置分流
        $buffer = 1024;        //来个文件字节计数器
        $count = 0;
        while(!feof($fp) && ($filesize-$count > 0)){
            $data = fread($fp,$buffer);
            $count += strlen($data);//计数
            echo $data;//传数据给浏览器端
        }
        fclose($fp);
    }


    /**
     * 字符转换（utf-8 => GBK）
     */
    public function utfToGbk($data) {
        return iconv('utf-8', 'GBK', $data);
    }
}